<?php
/**
 * HaB
 *
 * Gestor de contenidos de alta disponibilidad
 *
 * @package		HaB
 * @author		Oscar M. Lage <r0sk10@gmail.com>
 * @author		Marcos B.L. <marcosbl@gmail.com>
 * @version		1.0
 */

/**
 * functions.php
 *
 * Colección de funciones reusables
 *
 * @package		HaB
 * @version		1.0
 */

/**
 * Despachador de URLs
 */
function despachador()
{
	$request = ltrim($_SERVER['REQUEST_URI'], '/');
	$vars = explode('/', $request);
	
	// Eliminamos vacíos
	$request = array();
	foreach ($vars as $var)
		if($var!='')
			array_push($request, $var);
	if(!isset($request[0]))
		$req = DEFAULT_MOD; //header("Location: /".DEFAULT_MOD."/",TRUE,301);
	else
		if(file_exists(DIR_MODULES . $request[0])) $req = $request[0];
		else
		{
			//header("Location: /".DEFAULT_MOD. $_SERVER['REQUEST_URI'] ,TRUE,301);
			$req = DEFAULT_MOD;	
		}
	
	return array('module' => $req);
}

/**
 * Pinta la plantilla ($tpl) parseando las variables ($vars)
 */
function loadTemplate($tpl, $vars=null)
{
	global $conf;
	global $lang;
	
	$tpl = implode("", file($tpl));
	ob_start();
	if(!empty($vars)) extract($vars);
	eval("?>".$tpl."<?");
	$eval_buffer = ob_get_contents();
	ob_end_clean();
	return $eval_buffer;
}

/**
 * Pinta debug
 */
function debug($t_inicial)
{
	global $consultas;

	$t_final = round(microtime(), 6);
	$tiempoRender = $t_final - $t_inicial;
	$memoryRender = (memory_get_usage()/1024);

	echo '<div style="width: 700px; margin: 0px auto; text-align: center;">';

	// Tiempo de render y memoria consumida
	echo '<h1 onclick="$(\'#mem\').toggle();" style="cursor: pointer; text-align: left; background-color: #eee39b; padding: 1px 0 1px 5px; margin: 0 0 5px 0; font-size: 15px; border-bottom: 2px solid #9F9D6B">Resumen</h1>';
	echo '<div id="mem" style="padding: 10px; text-align: left; overflow: auto">';
	echo '  - <strong>Memoria consumida</strong>= <span style="color: #FF0000">'.$memoryRender.'</span> Kb.<br />';
	echo '  - <strong>Tiempo de render</strong> = <span style="color: #0099C9">' . $tiempoRender. '</span> microseg.<br />';
	if($consultas)
	{
		$tiempoSQL = 0;
		foreach($consultas as $con)
		{
			if($con['tiempo'])
				$tiempoSQL += $con['tiempo'];
		}
		echo '  - <strong>Tiempo SQL</strong>= <span style="color: #0099C9">'.$tiempoSQL.'</span> microseg.<br />';
		echo '  - <strong>Tiempo PHP</strong>= <span style="color: #0099C9">'.($tiempoRender-$tiempoSQL).'</span> microseg.<br />';
		echo '  - <strong>Nº consultas SQL</strong>= <span style="color: #FF0000">'.sizeof($consultas).'</span><br />';
	}
	echo '</div>';

	// SQL
	echo '<h1 onclick="$(\'#sql\').toggle();" style="text-align: left; cursor:pointer; background-color: #eee39b; padding: 1px 0 1px 5px; margin: 0 0 5px 0; font-size: 15px; border-bottom: 2px solid #9F9D6B">SQL</h1>';
	echo '<div id="sql" style="display: none; padding: 10px; height: 300px; overflow: auto;"><pre style="text-align: left">';
	if($consultas)
		print_r($consultas);
	echo '</pre></div>';
	
	// Superglobal $_GET
	echo '<h1 onclick="$(\'#get\').toggle();" style="text-align: left; cursor:pointer; background-color: #eee39b; padding: 1px 0 1px 5px; margin: 0 0 5px 0; font-size: 15px; border-bottom: 2px solid #9F9D6B">$_GET</h1>';
	echo '<div id="get" style="display: none; padding: 10px;"><pre style="text-align: left">';
	if($_GET) print_r($_GET);
	echo '</pre></div>';
	
	// Superglobal $_POST
	echo '<h1 onclick="$(\'#post\').toggle();" style="text-align: left; cursor: pointer; background-color: #eee39b; padding: 1px 0 1px 5px; margin: 0 0 5px 0; font-size: 15px; border-bottom: 2px solid #9F9D6B">$_POST</h1>';
	echo '<div id="post" style="display: none; padding: 10px;"><pre style="text-align: left">';
	if($_POST) print_r($_POST);
	echo '</pre></div>';
	
	// Superglobal $_SESSION
	echo '<h1 onclick="$(\'#session\').toggle();" style="text-align: left; cursor: pointer; background-color: #eee39b; padding: 1px 0 1px 5px; margin: 0 0 5px 0; font-size: 15px; border-bottom: 2px solid #9F9D6B">$_SESSION</h1>';
	echo '<div id="session" style="display: none; padding: 10px;"><pre style="text-align: left">';
	if($_SESSION) print_r($_SESSION);
	echo '</pre></div>';

	// Superglobal $_COOKIE
	echo '<h1 onclick="$(\'#cookie\').toggle();" style="text-align: left; cursor: pointer; background-color: #eee39b; padding: 1px 0 1px 5px; margin: 0 0 5px 0; font-size: 15px; border-bottom: 2px solid #9F9D6B">$_COOKIE</h1>';
	echo '<div id="cookie" style="display: none; padding: 10px"><pre style="text-align: left">';
	if($_COOKIE)
		print_r($_COOKIE);
	echo '</pre></div>';
	
	echo '<div class="">';
}


/*if (!function_exists('array_intersect_key'))
{
  function array_intersect_key($isec, $keys)
  {
    $argc = func_num_args();
    if ($argc > 2)
    {
      for ($i = 1; !empty($isec) && $i < $argc; $i++)
      {
        $arr = func_get_arg($i);
        foreach (array_keys($isec) as $key)
        {
          if (!isset($arr[$key]))
          {
            unset($isec[$key]);
          }
        }
      }
      return $isec;
    }
    else
    {
      $res = array();
      foreach (array_keys($isec) as $key)
      {
        if (isset($keys[$key]))
        {
          $res[$key] = $isec[$key];
        }
      }
      return $res;
    }
  }
}*/

/**
 * Sanador de variables
 */
function sanitizeSingle($var, $type)
{       
	switch (strtolower($type)) {
		case 'int': // integer
			$var = (int) $var;
			break;
		case 'str': // trim string
			$var = trim ( $var );
			break;
		case 'nohtml': // trim string, no HTML allowed
			$var = htmlentities ( trim ( $var ), ENT_QUOTES );
			break;
		case 'text': // trim string, no HTML allowed, plain text
			$var =  strip_tags( trim ( $var ))  ;
			break;
		case 'ucwords': // trim string, upper case words
			$var = ucwords ( strtolower ( trim ( $var ) ) );
			break;
		case 'ucfirst': // trim string, upper case first word
			$var = ucfirst ( strtolower ( trim ( $var ) ) );
			break;
		case 'lc': // trim string, lower case words
			$var = strtolower ( trim ( $var ) );
			break;
		case 'url': // trim string, url encoded
			$var = urlencode ( trim ( $var ) );
			break;
		case 'urlde': // trim string, url decoded
			$var = urldecode ( trim ( $var ) );
			break;
		case 'tlf': // True/False for a telephone number
			$size = strlen ($var) ;
			for ($x=0;$x<$size;$x++) {
				if ( ! ( ctype_digit($var[$x] ) || ($var[$x]==' ') || ($var[$x]=='(') || ($var[$x]==')')) ) {
					return false;
				}
			}
			break;
	}
	return $var;
}

/**
 * Sanador de variables
 */
function sanitize( &$data, $whatToKeep ) {
	$data = array_intersect_key( $data, $whatToKeep ); 
	foreach ($data as $key => $value) {
		$data[$key] = sanitizeSingle( $data[$key] , $whatToKeep[$key] );
	}
}



/*
// DEBUG
$_GET=array(
	"id" => 77,
    "name" => "Pepe",
    "surname1" => "<strong>Pepe & Hijos</strong>",
    "surname2" => "<strong>Pepe & Hijos</strong>",
    "tlf1" => "982-252016",
    "tlf2" => "(982) 252016",
    "ignored_var" => "I'm so useless...",
);


print_r($_GET);

sanitize($_GET, array( 'id'=>'int', 'name' => 'str', 'surname1' => 'nohtml', 'surname2' => 'text', 'tlf1' => 'tlf', 'tlf2' => 'tlf') );

print_r($_GET);
*/
?>